package com.zl.tby.core.common;

import com.zl.tby.core.exception.GlobalException;
import lombok.Data;
import org.noear.snack.ONode;
import org.noear.snack.core.utils.StringUtil;
import org.noear.solon.core.handle.Context;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Data
public class User {

    private final static String USER_INFO_KEY = "User-Info";
    /**
     * 用户id
     */
    private Long userId;
    /**
     * 用户名
     */
    private String username;
    /**
     * 昵称
     */
    private String nickname;
    /**
     * 部门id
     */
    private String deptId;
    /**
     * 区域id
     */
    private String areaId;
    /**
     * 电话号
     */
    private String phone;
    /**
     * 邮箱
     */
    private String email;
    /**
     * 部门名称
     */
    private String deptName;
    /**
     * 区域名称
     */
    private String areaName;
    /**
     *
     */
    private String avatar;
    /**
     * 部门级别
     */
    private Integer deptLevel;
    /**
     * 区域级别
     */
    private Integer areaLevel;
    /**
     * 角色编码
     */
    private String role;

    /**
     * 获取当前用户
     */
    public static User current() {
        Context ctx = Context.current();
        var user = (User) ctx.attr(USER_INFO_KEY);
        if (user != null) {
            return user;
        }
        String temp = ctx.header(USER_INFO_KEY);
        if (StringUtil.isEmpty(temp)) {
            throw new GlobalException("请求失败：未登录", 400);
        }
        String decode = new String(Base64.getDecoder().decode(temp), StandardCharsets.UTF_8);
        user = ONode.deserialize(decode, User.class);
        ctx.attrSet(USER_INFO_KEY, user);
        return user;
    }

}
